import _ from 'lodash';
import {message} from 'antd';
import {observable, action} from 'mobx';
import {toPlainObjectDeep} from '../../../utils/toPlainObjectDeep';
import {UserBean, UserSearchBean, UserController} from '../../../model/user/User';
import {AdAppPositionController} from '../../../model/ad/adPosition/AdAppPositionController'
import {FormStore, ListStore, FieldItem, isRequired, isSelectRequired, toJSDeep} from '../../common/store/Store';
import {mobileValid, repPsdValid} from '../../../utils/validator/Validator';

const userController = new UserController();
const adAppPositionController = new AdAppPositionController();

export class UserFields implements UserBean<FieldItem> {
    constructor(type = 'add'){
        if(type === 'edit'){
            _.forEach(this, (field:FieldItem, key: string) => {
                if(field.hasFeedback === true){
                    field.validateStatus = 'success';
                }
            })  
        }
    }

    id: FieldItem = new FieldItem({
        value: null
    });
    username: FieldItem = new FieldItem({
        value: '',
        required: true,
        hasFeedback: true
    });
    realname: FieldItem = new FieldItem({
        value: '',
        required: true,
        hasFeedback: true
    });
    originalPassword: FieldItem = new FieldItem({
        value: '',
        required: true,
        hasFeedback: true
    });
    password: FieldItem = new FieldItem({
        value: '',
        required: true,
        hasFeedback: true,
        disabled: false
    });
    resPassword: FieldItem = new FieldItem({
        value: '',
        required: true,
        hasFeedback: true,
        disabled: false
    })
    mobile: FieldItem = new FieldItem({
        value: '',
        required: true,
        hasFeedback: true
    });
    businessIds: FieldItem = new FieldItem({
        value: [],
        required: true,
        hasFeedback: true,
        option: []
    });
}

export class UserSearchFields implements UserSearchBean<FieldItem>{
    username: FieldItem = new FieldItem({
        value: ''
    });
}

const addDefaultFields = toPlainObjectDeep(new UserFields());
const editDefaultFields = toPlainObjectDeep(new UserFields('edit'));

export class UserBaseFormStore extends FormStore<UserFields, UserBean<any>> {
    @observable confirmLoading:boolean = false;

    @action changeConfirmLoading(params){
        this.confirmLoading = params;
    }

    validators = {
        mobile:[isRequired,mobileValid],
        businessIds: [isRequired],
        realname: [isRequired]
    };

    /*=====================bu的datasource=====================*/
    @action getAllBu(partnerId = null){
        return adAppPositionController
            .getAllbuList({partnerId:partnerId})
            .then((data)=>{
                this.fields.businessIds.option = this.fields.businessIds.option.concat(_.map(data.result,map));
                return data;
            })

        function map(item){
            return {
                key: _.toString(item.id),
                title: item.title,
                description: item.description
            }
        }
    }

    /*======================校验==============================*/

    checkUsername(username){
        return userController.checkUsername({
            username: username
        }).then((data)=>{
            if(!data.success){
                return data.message;
            }else{
                return true;
            }
        })
    }

    checkPassword(me){
        return function(password){
            let id = _.parseInt(me.fields.id.value);

            if(!!password || password === 0){
                return userController.checkPassword({
                    id: id,
                    password: password
                }).then((data)=>{
                    if(!data.success){
                        return data.message;
                    }else{
                        return true;
                    }
                })
            }
        }
    }

    @action bindData(){
        this.changeFields({
            username: { disabled: true },
            password: { disabled: true },
            resPassword: { disabled: true }
        });

        this.getAllBu();
    }
}

export class Add extends UserBaseFormStore {
    
    validators = _.assign({},this.validators,{
        username: [isRequired,this.checkUsername],
        password: [isRequired, repPsdValid(this, 'resPassword')],
        resPassword: [isRequired, repPsdValid(this, 'password')]
    })

    defaultFields = _.cloneDeep(addDefaultFields);

    @observable fields: UserFields = _.cloneDeep(addDefaultFields);

    @action addBu(params:UserBean<any>){
        return userController.addUser(params);
    }

    @action load(){
         this.show();

         setTimeout(()=>{
             this.getAllBu()
         },100);
    }
}

export class Edit extends UserBaseFormStore {

    validators = _.assign({},this.validators,{
        username: [isRequired],
        originalPassword: [this.checkPassword(this)],
        password: [repPsdValid(this, 'resPassword')],
        resPassword: [repPsdValid(this, 'password')]
    });

    defaultFields = _.cloneDeep(editDefaultFields);

    @observable fields: UserFields = _.cloneDeep(editDefaultFields);

    @action load(id: number) {
        userController.getUser({id:id}).then((res) => {
            if(res.success){
                let data = res.result;

                this.show(_.assign(data,{
                    businessIds: _.map(data.businessIds,_.toString),
                    password: ''
                }));

                setTimeout(()=>{
                    this.bindData();
                },100);
            }else{
                message.error(res.message,3);
            }
        })
    }

    @action editBu(params:UserBean<any>){
        return userController.editUser(params);
    }
}

class Check extends UserBaseFormStore {
    @observable fields: UserFields = _.cloneDeep(addDefaultFields);
}

export class List extends ListStore<UserBean<any>> {
    @action searchUserList(params?:any){
        this._SpiLoading = true;

        userController.searchUserList(params).then((data) =>{
            this.searchCallback(data);
        })
    }

    @action delete(id: number){
       return userController.deleteUser({id:id});
    }

    @action load(params:any = {}){
        this.searchUserList(params);
    }

    @action refresh(search: Search){
        this.changeState(true);
        search.clearAll();
        this.load();
    }
}

const searchDefaultFields = toPlainObjectDeep(new UserSearchFields());

class Search extends FormStore<UserSearchFields,UserSearchBean<any>>{
    
    defaultFields = _.cloneDeep(searchDefaultFields);

    @observable fields: UserSearchFields = _.cloneDeep(searchDefaultFields);

    @observable expand:boolean = false;

    @action OnExpand(expand){
        this.expand = !expand;
    }

    @action clearSearch(list:List){
        this.clearAll();
        list.load();
    }

    @action clearSearchState(){
        this.expand = false;
        this.clearAll();
    }
}


export const listStore = new List();
export const addStore = new Add();
export const editStore = new Edit();
export const checkStore = new Check();
export const searchStore = new Search();